
/**
 * Module dependencies.
 */
var mdulePath = '/usr/local/lib/node_modules/';

var express = require(mdulePath+'express')
  , routes = require('./routes')
  , http = require('http')
  , path = require('path')
  , model = require('./models');

var app = express();
var server = http.createServer(app);
var io = require(mdulePath+'socket.io').listen(server);
var hash = require('./hash.js').hash;
var logger = require(mdulePath+'morgan');

app.use(logger());
app.set('port', process.env.PORT || 8001);
app.set('views', __dirname + '/views');
app.engine('html', require(mdulePath+'ejs').renderFile);
app.set('view engine', mdulePath+'ejs');
app.use(express.static(__dirname + '/public'));

routes(app);
server.listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});
var userModel = model.userModel;
var courseModel = model.courseModel;
var putQuestionModel = model.putQuestionModel;
var makeTeamModel = model.makeTeamModel;
function getType(o) { 
  var _t; 
  return ((_t = typeof(o)) == "object" ? o==null && "null" || Object.prototype.toString.call(o).slice(8,-1):_t).toLowerCase(); 
}
function diffArray(a,b){
  //求a和b的差异集合,即a-b
  if((getType(a) != 'array')||(getType(b) != 'array')){return null;}
  var aNum = a.length;
  var bNum = b.length;
  if(aNum<bNum){return null;}
  var ret = [];
  var tmp = [];
  for(var i = 0; i < bNum; i++){
    tmp[b[i]] = true;
  }
  for(var i = 0; i < aNum; i++){
    if(!tmp[a[i]]){
      ret.push(a[i]);
    }
  }
  return ret;
}
var pieTime = function(){
  var curTime = new Date();
  var year = curTime.getFullYear();
  var month = curTime.getMonth()+1;
  if(month<10){
    month = '0'+month;
  }
  var date = curTime.getDate();
  if(date<10){
    date = '0'+date;
  }
  var hour = curTime.getHours();
  if(hour<10){
    hour = '0'+hour;
  }
  var minute = curTime.getMinutes();
  if(minute<10){
    minute = '0'+minute;
  }
  var second = curTime.getSeconds();
  if(second<10){
    second = '0'+second;
  }
  var result = year+'-'+month+'-'+date+' '+hour+':'+minute+':'+second;
  return result;
}
Array.prototype.find = function(ele){
  var len = this.length;
  for(var i = len-1; i >= 0; i--){
    if(this[i] == ele){
      return i;
    }
  }
  return -1;
}
function output(data){
  for(var key in data){
    console.log(key+'='+data[key]);
  }
}
io.on('connection',function(socket){
  //为了安全考虑应该在各处验证数据的合法性
  var curAccount = null;   //当前连接对应唯一用户的account
  var curNickname = null; //当前用户的昵称
  var verified = false;  //标记当前连接是否经过验证,若为false不响应任何请求
  socket.emit('connected');
  socket.on('disconnect',function(){
    if(!verified){return;}
    userModel.findOne({'account':curAccount},function(err,user){
      if(err){
        socket.emit('systemError');
        return;
      }
      if(user){
        verified = false;
        if(socket.id == user.socketId){
          user.socketId = null;
          user.save();
        }
      }
    });
  });
});